# -*- coding: utf-8 -*-
# Create your views here.
from models import Salesperson,Wellcome_mail,Salesperson_groups,Role #import models Salesperson_groups  huangzy edit
from crm.models import Maillist,Maillog,Mailfile
from crm.models import Members,Projects,Follow_up
from django.shortcuts import render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django import forms
import re
import reg_allocation
from crm.models import Agent
#from form.models import Place
from django.conf import settings
import md5,random,md5,datetime

import role_cfg as rcfg

import os
import email
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import Encoders
import smtplib
import urllib2


#同一人名与samecode为同一人.用于识别一人报了多个project
def getsamecode ():
    nowtime=datetime.datetime.now()
    pname=str(nowtime)+str(random.randrange(1,100000))
    pname=md5.new(pname).hexdigest()
    tname=pname[:10].lower()
    return tname

def co (x):
    x = x.decode('gbk').encode('UTF-8')
    return x

def test(request):
    return render_to_response('error/test.html')

def loginpage (request):
    return render_to_response('login.html')

def checklogin (request):
    post_data = request.POST.copy()
    inputpassword=post_data['password']
    sales=Salesperson.objects.filter(name=post_data['name'])
    if not sales:
        flashmsg="No such user! "
        return render_to_response('login.html',{'flashmsg': flashmsg})
    else:
        sales2=Salesperson.objects.filter(name=post_data['name'],password=inputpassword)
        if not sales2:
            flashmsg="Password is no true! "
            return render_to_response('login.html',{'flashmsg': flashmsg,'name':post_data['name']})
        else:
            """ set session """
            salesinfo=Salesperson.objects.get(name=post_data['name'])
            try:
                role = Role.objects.get(name=salesinfo.level)
            except KeyError:
                print KeyError
                sys.exit()
            request.session['id'] = salesinfo.id
            request.session['name'] = post_data['name']
            request.session['level'] = salesinfo.level
            request.session['role_id'] = role.role_ids
            request.session['menus'] = ''
            #request.session['role_id'] = '100,1001,10001,10002,20002,1002'
            request.session['group'] = salesinfo.group  #set default group
##            if salesinfo.level=='sales':#如果是sales,登陆后选择program
##                return HttpResponseRedirect('/program/')
#            else:
#                return HttpResponseRedirect('/index/')
#            return HttpResponseRedirect('/program/')  去掉登录后的项目选择  huangzy edit
            return HttpResponseRedirect('/index/')

def program(request):#选择program
    if request.method == 'GET':
        program=Projects.objects.order_by('id')
        return render_to_response('set_program.html',{'program':program})
    else:
        pid=request.POST.get('pid')
        if pid:
            request.session['program'] = pid
            return HttpResponseRedirect('/index/')
        else:
            return HttpResponseRedirect('/program/')

def logout(request):
    try:
        del request.session['id']
        del request.session['name']
        del request.session['level']
        del request.session['program']
    except KeyError:
        pass
    return HttpResponseRedirect('/')


def admin_index (request):
    try:
        request.session['id']
        request.session['group']
        request.session['program'] = 3 #去掉登录后的项目选择 huangzy edit
    except:
        return HttpResponseRedirect('/')
    return render_to_response('admin_index.html')

def admin_menu (request):
    name=request.session['name']
    level=request.session['level']
    p_id=request.session['program']
	#ret = request.session['menus']

# --> 权限系统开始 <-- #
    b = request.session['role_id']
    a = b.split(',')
    menu = rcfg.role_id
    ret = list(rcfg.role_id)
    if request.session['level']=="administrators":
        ret = menu
    else:
        for (i,item) in enumerate(menu):
            if item:
                if a.count(item['code'])<1:
                    ret[i]=''
                else:
                    for (j,jtem) in enumerate(item['content']):
                        if jtem:
                            if a.count(jtem['code'])<1:
                                ret[i]['content'][j]=''
                            elif jtem.has_key('type'):
                                continue
                            else:
                                for (kk,ktem) in enumerate(jtem['content']):
                                    if ktem:
                                        if a.count(ktem['code'])<1:
                                            ret[i]['content'][j]['content'][kk]=''

# --> 权限系统结束 <-- #
    return render_to_response('admin_menu.html',{'level':level,'name':name,'p_id':p_id,'menu':ret})

def admin_top (request):
    #分配给该SALE.但没follow up的客户
    m_list=[]
    if request.session['level']=='sales':
        mm_list=Members.objects.filter(salesperson__id=request.session['id']).order_by('-id')[:30]
        for mm in mm_list:
            f_list=Follow_up.objects.filter(members__id=mm.id).order_by('id')
            if not f_list.count():
                m_list.append(mm)
    return render_to_response('admin_top.html')

def admin_drag (request):
    return render_to_response('admin_drag.html')

def admin_main (request):
    return render_to_response('main.html')

def gosendsms (salemobile='',cname='',pname='',t_h='',t_o='',t_m=''):
    from SendSMS import *
    import SendSMS
    username = "chinaedu1"
    password = "6nDGpAL1"
    print salemobile
    try:
        # Initialise the library
        print "Initialising library..."
        SendSMS.init(username,password)
        print "Library initialised."

        # Send a message to 447000000001 with sender 'James' and message 'Hello'
        # SourceTON (type of number) will be set automatically by the library.
        #destination = "447000000001"
        destination=salemobile
        source ="crm"
        message =cname+','+pname+',tel_h:'+t_h+',o:'+t_o+',m:'+t_m+'.'
        print message
        print "Sending message...";
        responses = sendSMS({ 'da': destination, 'sa': source, 'm': message })
        print "Message sent.";

        # Print the response to the screen
        print "Responses from the server:"
        for response in responses:
            print "\t" + response
    except SMSClientError, e:
        print e



    #接受客户注册信息
def crmregister (request):
    issdf_id=0
    if request.method == 'POST':
            new_data = request.POST.copy()
            projectids=new_data.getlist('projectids')
            issdf_id=0#测试斯坦福的广告效果
            samecode=getsamecode()
            new_data['attendsess']=request.POST.get('attendsess','N')
            if new_data['attendsess'] != 'N':
                new_data['attendsess'] = 'Y'
            new_data['moreinform']=request.POST.get('moreinform','0')
            new_data['agent_id'] = request.POST.get('agent_id','0')
            new_data['agent'] = request.POST.get('agent','')
            new_data['project_id'] = request.POST.get('project_id','0')
            try:
                if int(new_data['project_id'])==3:
                    issdf_id=3
            except:
                issdf_id=0
            job_title_value = request.POST.get('job_title','')
            new_data['company'] = request.POST.get('company','')
            #new_data['attendsess'] = request.POST.get('attendsess','N')
            new_data['address'] = request.POST.get('address','')
            #M&T多出的字段
            new_data['message'] = request.POST.get('message','')
            #new_data['mba'] = request.POST.get('mba','0')
            #new_data['mpa'] = request.POST.get('mpa','0')
            #new_data['dba'] = request.POST.get('dba','0')
            #按优先级先查出所有project
            allproject_list=Projects.objects.filter().order_by("-imvalue")
            ppid_list=[]
            pid_list=[]
            if projectids:
                for i,pid in enumerate(projectids):
                    try:
                        pid=int(pid)
                    except:
                        pass
                    ppid_list.append(pid)
                for p in allproject_list:
                    if p.id in ppid_list:
                        pid_list.append(p.id)
            else:
                pid_list.append(new_data['project_id'])
            
            #return HttpResponse(str(projectids))
            for pid in pid_list:
                """验证数据类型是否合法"""
                pid=int(pid)
                errormsg=''
                if int(len(new_data['name']))>30 or int(len(new_data['name']))<2:
                    errormsg=errormsg+'The name should be 2~25 charaters<br />'
                c = re.compile('\D')
                m = c.findall(new_data['tel_h'])
                m2 = c.findall(new_data['tel_o'])
                m3 = c.findall(new_data['tel_m'])
                if m or m2 or m3:
                    errormsg=errormsg+'The telephone number must be Digital<br />'
                if new_data['email']=='':
                    errormsg=errormsg+'input email please<br />'
                p=re.compile(r'^[_a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3})$')
                me=p.match(new_data['email'])
                if me==None:
                    errormsg=errormsg+'Your Email address is not correct<br />'
                #检查是否重复数据.
                #sales2=Members.objects.filter(name=new_data['name'],tel_h=new_data['tel_h'],tel_o=new_data['tel_o'],tel_m=new_data['tel_m'],email=new_data['email'])
                mlist=Members.objects.order_by('-id')[:1]
                lastid=''
                for m in mlist:
                    lastid=m.id
                if lastid:
                    try:
                        last_obj=Members.objects.get(pk=lastid)
                    except:
                        last_obj=''
                if last_obj:
                    try:
                        last_pid=last_obj.projects.id
                        if last_obj.name==new_data['name'].strip() and last_obj.tel_h==new_data['tel_h'] and last_obj.tel_o==new_data['tel_o'] and last_obj.tel_m==new_data['tel_m'] and last_obj.email==new_data['email'].strip() and last_pid==pid:
                            errormsg=errormsg+"Your had post the info just now ,Dont't post again please<br />"
                    except:
                        pass
                if errormsg!='':
                    return render_to_response('flash.html',{'flashmsg':errormsg})
                
                # <- begin group ->
                salesgroups = Salesperson_groups.objects.order_by('id')   #add reg area huangzy edit
                if request.META.has_key('HTTP_X_FORWARDED_FOR'):  
                    ip =  request.META['HTTP_X_FORWARDED_FOR']  
                else:  
                    ip = request.META['REMOTE_ADDR']
                #ip = '58.60.3.101'
                #sql = '''select * from ip where s <= inet_aton('%s') and e>=inet_aton('%s')'''%(ip,ip)
                #from django.db import connection, transaction
                #cursor = connection.cursor()
                #cursor.execute(sql) 
                #ip_area = cursor.fetchone()
		
                #groups = {}
                #group = ''
                #for a in salesgroups:
                    #'''根据来路的agent来取得相应的sales组id,如果没有对应的值则为HK'''
                    #if (new_data['agent']=='' or new_data['agent'].upper()=='WEB') and (new_data['tel_h'].find('886')==-1 and new_data['tel_o'].find('886')==-1 and new_data['tel_m'].find('886')==-1) and (new_data['tel_h'].find('86')==-1 and new_data['tel_o'].find('86')==-1 and new_data['tel_m'].find('86')==-1 and new_data['tel_h'].find('0')!=0 and new_data['tel_o'].find('0')!=0 and new_data['tel_m'].find('0')!=0):
                        #if ip_area[5].find(a.chinese)!=-1:
                            #group = a.id
                            #break
                        #else:
                            #pass
                    #elif new_data['agent'].upper().find(a.code.upper())!=-1:
                        #group = a.id
                        #break
                    #groups[a.code.upper()] = a.id
                
                #if group=='':
                    #if new_data['tel_h'].find('886')!=-1 or new_data['tel_o'].find('886')!=-1 or new_data['tel_m'].find('886')!=-1:
                        #group = groups['TW']
                    #elif new_data['tel_h'].find('86')!=-1 or new_data['tel_o'].find('86')!=-1 or new_data['tel_m'].find('86')!=-1 or new_data['tel_h'].find('0')==0 or new_data['tel_o'].find('0')==0 or new_data['tel_m'].find('0')==0:
                        #group = groups['SZ']
                    #else:
                        #group = groups['HK']
		groups = {}
                group = ''
                for a in salesgroups:
		    if new_data['agent'].upper().find(a.code.upper())!=-1:
                        group = a.id
                        break
                    groups[a.code.upper()] = a.id
		if group=='':
		    group = groups['HK']
                # <- end group ->

                #pid=int(new_data['project_id'])
                autotosales=0
                if new_data['agent']=='emd':
                    sale_id=9
                    autotosales=1
                if autotosales==0:
                    #自动分配sales
                    #把samecode传过去识别是否一人报多个project. 把这人都尽量分给同一sales
                    if pid==3 or pid==4 or pid==10 or pid==16 or pid==18 or pid==17:
                        sale_id=reg_allocation.allocation_reg(pid,new_data['name'],samecode,new_data['email'],group)
                    else:
                        sale_id=0
                if new_data['agent']!='':
                    try:
                        agent_obj,created=Agent.objects.get_or_create(name=new_data['agent'],defaults={'name':new_data['agent'],'intro':'','budget':0})
                        new_data['agent_id']=agent_obj.id
                    except:
                        new_data['agent_id']=0

                try:
                    project_obj=Projects.objects.get(pk=pid)
                    pname=project_obj.name
                except:
                    pname=''
                
                member=Members(
                salesperson_id=sale_id,
                name=new_data['name'],
                job_title=job_title_value,
                company=new_data['company'],
                tel_h=new_data['tel_h'],
                tel_o=new_data['tel_o'],
                tel_m=new_data['tel_m'],
                email=new_data['email'],
                address=co(new_data['address']),
                attendsess = new_data['attendsess'],
                status='0',
                interlevel='0',
                work_experience='0',
                agent_id=new_data['agent_id'],
                projects_id=pid,
                regtime=datetime.datetime.now(),
                last_contact=datetime.datetime.now(),
                mba=0,
                mpa=0,
                dba=0,
                message=new_data['message'],
                samecode=samecode,
                men_area = group,
                men_ip = ip,
                )
                member.save()
                
                if sale_id!=0:
                    #有分配SALES,查看该SALES是否需要发短信通知.
                    try:
                        sales_obj=Salesperson.objects.get(pk=sale_id)
                    except:
                        sales_obj=''
                    if sales_obj:
                        sendsms=sales_obj.sendsms
                        if sendsms:
                            #发送短信通知.
                            #pass
                            gosendsms(sales_obj.mobile,new_data['name'],pname,new_data['tel_h'],new_data['tel_o'],new_data['tel_m'])
                            #发送短信通知.
                    #自动发送该sales设定的邮件.
                        try:
                            wm_obj=Wellcome_mail.objects.get(program__pk=int(pid),sales=sales_obj)
                            if int(wm_obj.autosendmail)==1:
                                """
                                from django.core.mail import send_mail as core_send_mail
                                from django.template import Template, Context
                                t = Template('Dear {{customer}},\n{{wm.maincontent}}\n{{wm.thanks}}\nBest regards,\n{{sales_obj.name}}\n{{wm.address}}\nEmail:{{sales_obj.name}}@chinaedugrp.com\n Website:{{wm.site}}\n')
                                subject=wm_obj.title
                                core_send_mail(subject, t.render(Context({'wm': wm_obj,'sales_obj':sales_obj,'customer':new_data['name']})), sales_obj.name, [new_data['email']])
                                """
                                subject=wm_obj.title
                                authInfo = {}
                                authInfo['server'] = settings.EMAIL_HOST
                                authInfo['user'] = settings.EMAIL_HOST_USER #用户名
                                authInfo['password'] = settings.EMAIL_HOST_PASSWORD #密码
                                fromAdd = str(sales_obj.name)+"@chinaedugrp.com"  #邮箱地址
                                toAdd = [new_data['email']]
                                subject = subject
                                #files = ['urls.py']
                                #files=''
                                files=[]
                                if wm_obj.fileurl:
                                    print str(wm_obj.fileurl)
                                    fp=str(os.getcwd())+str(wm_obj.fileurl)
                                    files.append(fp)
                                else:
                                    files=''
                                #plainText = '这里是普通文本'
                                htmlText = wm_obj.maincontent.replace('\n', '<br />') or ''
                                sendEmail(authInfo, fromAdd, toAdd, subject, files, htmlText)
                                #记录
                                maillog_obj=Maillog(
                                members=member,
                                sales=sales_obj,
                                addtime=datetime.datetime.now(),
                                sendtime=datetime.datetime.now(),
                                tomail=new_data['email'],
                                subject=subject,
                                mailbody=htmlText,
                                dontsend=0,
                                automail=1,
                                )
                                maillog_obj.save()
                        except:
                            pass
            return render_to_response('flash.html',{'flashmsg':"Has been submitted,We will contact you as soon as possible",'goback':1,'issdf_id':issdf_id})
    else:
        return render_to_response('flash.html',{'flashmsg':"error page",'goback':1,'issdf_id':0})


#send email

def sendEmail(authInfo, fromAdd, toAdd, subject,files, htmlText):

    strFrom = fromAdd
    strTo = ', '.join(toAdd)

    server = authInfo.get('server')
    user = authInfo.get('user')
    passwd = authInfo.get('password')

    if not (server and user and passwd) :
            print 'incomplete login info, exit now'
            return

    # 设定root信息
    msgRoot = MIMEMultipart('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = strFrom
    msgRoot['To'] = strTo
    msgRoot.preamble = 'This is a multi-part message in MIME format.'

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

#    #设定纯文本信息
#    msgText = MIMEText(plainText, 'plain', 'utf-8')
#    msgAlternative.attach(msgText)

    #设定HTML信息
    msgText = MIMEText(htmlText, 'html', 'utf-8')
    msgAlternative.attach(msgText)

    #设定附件信息
    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        msgAlternative.attach(part)

    #发送邮件
    smtp = smtplib.SMTP()
    #设定调试级别，依情况而定
    smtp.set_debuglevel(1)
    smtp.connect(server)
    smtp.login(user, passwd)
    smtp.sendmail(strFrom, strTo, msgRoot.as_string())
    smtp.quit()
    return





def testmail (request):
    from django.core.mail import send_mail as core_send_mail
    subject='test auto mail'
    message_body='mail content'
    from_address='automail'
    to_address='quitecome@qq.com'
    #core_send_mail(subject, message_body, from_address, [to_address])
    from django.template import Template, Context
    t = Template('<html><p>{{wm}}</p>{{thx}}</html>')
    core_send_mail(subject, t.render(Context({'wm': co('试试中文tttttt试试中文'),'thx':co('\n谢谢')})), 'chinaedugrp', ['jhzhang@staff.netbig.com'])
    return HttpResponse('ok2')

